const mongoose = require('mongoose')
const base = require('../base')
const fss = require('../tools/fss')
const path = require('path')
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
    //唯一的
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  name: {
    type: String,
  },
  userimg: {
    type: String
  }
}, { timestamps: { createdAt: 'create_time', updatedAt: 'update_time' } })



const User = mongoose.model("users", UserSchema)
// 读取文件并创建一条用户数据
const url = path.join(__dirname,'../rootinfo/admin.json')
fss.read(url).then((rootdata) => {
  const userinfo = {
    username: '',
    password: '',
    email: '',
    role: '',
    userimg: '',
    name:''
  }
  userinfo.username = JSON.parse(rootdata)['username']
  userinfo.password = JSON.parse(rootdata)['password']
  userinfo.email = JSON.parse(rootdata)['email']
  userinfo.role = JSON.parse(rootdata)['role']
  userinfo.name = JSON.parse(rootdata)['name']
  //把图片的地址存入数据库，拼接上域名
  userinfo.userimg = base.baseIP + JSON.parse(rootdata)['userimg']

  User.findOne({ username: userinfo.username }).then((result) => {
    if (result) {
      console.log(`用户 ${userinfo.username} 已存在`);
      return null;
    } else {
      return User.create(userinfo).then((user) => {
        console.log('创建管理员用户成功', user);
        return user;
      });
    }
  }).catch((err) => {
    res.send({ msg: '读取失败', status: 406 })
  })
})

module.exports = User
